package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.dao.ShoppingCartDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.ShoppingCart;
import com.itheima.pojo.User;
import com.itheima.service.ShoppingCartService;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Service
public class ShoppingCartImpl extends ServiceImpl<ShoppingCartDao, ShoppingCart>  implements ShoppingCartService {
    @Autowired
    ShoppingCartDao shoppingCartDao;

    /**
     * 添加购物车
     */
    @Override
    public ShoppingCart add(ShoppingCart shoppingCart) {
        //获取用户id
        Long userId = (Long) BaseContext.getCurrentId();
//        菜品或者套餐是否点过
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,userId);
        if(shoppingCart.getDishId() != null){    //点的是菜品
            wrapper.eq(ShoppingCart::getDishId,shoppingCart.getDishId());
        }else { //点的是套餐
            wrapper.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        }
        ShoppingCart one = shoppingCartDao.selectOne(wrapper);
        if(one == null){    //第一次点，直接添加到购物车
            shoppingCart.setNumber(1);
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartDao.insert(shoppingCart);
        }else { //点过，增加数量
            one.setNumber(one.getNumber() + 1);
            shoppingCartDao.updateById(one);
        }
        //获取添加到数据库中数据
        ShoppingCart one1 = shoppingCartDao.selectOne(wrapper);
        return one1;


    }

    /**
     * 取消购物车
     */
    @Override
    public ShoppingCart cancelShoppingCat(ShoppingCart shoppingCart) {
        //获取用户id
        Long userId = (Long) BaseContext.getCurrentId();
//        菜品或者套餐是否点过
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,userId);
        if(shoppingCart.getDishId() != null){    //点的是菜品
            wrapper.eq(ShoppingCart::getDishId,shoppingCart.getDishId());
        }else { //点的是套餐
            wrapper.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        }
        ShoppingCart one = shoppingCartDao.selectOne(wrapper);
        Integer number = one.getNumber();
        number--;
        one.setNumber(number);
        if(number > 0){
            shoppingCartDao.updateById(one);
        }else { //
            shoppingCartDao.delete(wrapper);
        }
        return one;
    }


}
